package com.lz.controller;

import com.lz.constant.CookieConstant;
import com.lz.constant.RedisConstant;
import com.lz.entity.SellerInfo;
import com.lz.enums.ResultEnum;
import com.lz.service.SellerService;
import com.lz.utils.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 卖家用户控制层
 * Created by Administrator on 2018/9/6 0006.
 */
@Controller
@RequestMapping("/seller")
@Slf4j
public class SellerUserController {

    @Autowired
    private SellerService sellerService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 登陆方法
     * @param openid
     * @param model
     * @param response
     * @return
     */
    @GetMapping("/login")
    public String login(@RequestParam("openid")String openid, Model model,
                        HttpServletResponse response){
        log.info("【登陆方法不拦截】");
        //1.数据库匹配openid
        SellerInfo sellerInfoByOpenid = sellerService.findSellerInfoByOpenid(openid);
        if (sellerInfoByOpenid == null){
            model.addAttribute("msg", ResultEnum.LOGIN_FAIL.getMessage());
            model.addAttribute("url","/seller/order/list");
            return "common/error";
        }
        //2.设置token到redis
        String token = UUID.randomUUID().toString();
        Integer expire = RedisConstant.EXPIRE;
        stringRedisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX,token),openid,expire,TimeUnit.SECONDS);
        //3.设置token到cookie
        CookieUtil.set(response, CookieConstant.TOKEN,token,expire);
        return "redirect:/seller/order/list";
    }

    /**
     * 登出方法
     * @param request
     * @param response
     * @param model
     * @return
     */
    @GetMapping("/logout")
    public String logout(HttpServletRequest request,HttpServletResponse response,Model model){
        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
        if (cookie != null){
            //清除redis中token
            stringRedisTemplate.opsForValue().getOperations().delete(String.format(RedisConstant.TOKEN_PREFIX,cookie.getValue()));
            //清除cookie
            CookieUtil.set(response,CookieConstant.TOKEN,null,0);
        }
        model.addAttribute("msg",ResultEnum.LOGOUT_SUCCESS.getMessage());
        model.addAttribute("url","/seller/order/list");
        return "common/success";
    }
}
